<template>
    <div class="dhzn_farmer">

        <!-- <div class="dh_c-nav">
            <el-menu :default-active="activecoupon" class="el-menu-demo" mode="horizontal" @select="handleSelect">
                <el-menu-item :class="(item.id == activecoupon ? 'dh_gln-active' : '')" v-for="(item,key) in classify" :key="key" :index="item.id.toString()">{{item.name}}</el-menu-item>
            </el-menu>
        </div> -->

        <!-- 查询 -->
        <div class="dh-c-addfarmer bcwh mb10">
            <el-form label-width="80px" :inline="true" :model="formfarmer" :rules="rules" ref="formfarmer" class="pt20">

                <el-form-item label="查询条件">
                        <el-select v-model="formfarmer.region" @change="resetForm('formfarmer')" placeholder="选择查询条件">
                            <el-option label="农户ID" value="1"></el-option>
                            <el-option label="农户名称" value="2"></el-option>
                            <el-option label="农户地址" value="3"></el-option>
                            <!-- <el-option label="入驻时间" value="4"></el-option> -->
                        </el-select>
                </el-form-item>

                <el-form-item label="农户ID" v-if="formfarmer.region == 1" prop="id">
                    <el-input placeholder="请输入查询的农户ID" v-model="formfarmer.id" clearable></el-input>
                </el-form-item>

                <el-form-item label="农户名称" v-else-if="formfarmer.region == 2" prop='name'>
                    <el-input placeholder="请输入查询的农户名称" v-model="formfarmer.name" clearable></el-input>
                </el-form-item>
                    
                <el-form-item label="农户地址" v-else-if="formfarmer.region == 3" prop="address">
                    <el-input placeholder="请输入查询的农户地址" v-model="formfarmer.address" clearable></el-input>
                </el-form-item>
                    
                <!-- <el-form-item v-else label="时间范围">
                    <el-col :span="11">
                        <el-form-item prop="date1">
                            <el-date-picker type="date" placeholder="选择日期" v-model="formfarmer.date1" style="width: 100%;" clearable></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col class="line tc" :span="1">-</el-col>
                    <el-col :span="11">
                        <el-form-item prop="date2">
                            <el-time-picker placeholder="选择时间" v-model="formfarmer.date2" style="width: 100%;" clearable></el-time-picker>
                        </el-form-item>
                    </el-col>
                </el-form-item> -->

                <el-form-item>
                    <el-button type="primary" @click="farmerquery('formfarmer')">查询</el-button>
                    <el-button @click="resetForm('formfarmer'),requestfarmer()">取消</el-button>
                </el-form-item>                

            </el-form>
        </div>

        <!-- 内容页 -->
        <div class="dh_c-content">
            <!-- 查询预览 -->
            <div class="dh_c-c-details">

                <div class="dh_ccd-title">
                    <button class="bc4a wh p5 br5" @click="dialogVisible = true;for(var i in addfarmer) addfarmer[i] = ''">添加农户</button>
                </div>

                <!-- <div class="dh_ccd-radio">
                    <el-radio v-model="radio" label="1">以被领取</el-radio>
                    <el-radio v-model="radio" label="2">未被领取</el-radio>
                </div> -->
                <table class="dh_ccd-table f14 tc" cellspacing="0" cellpadding="0" border="1">
                    <thead>
                        <tr>
                            <th>农户ID</th>
                            <th>农户名称</th>
                            <th>农户地址</th>
                            <th>入驻时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    
                    <tbody>
                        <tr v-for="(item,key) in farmerdata" :key="key">
                            <td>{{item.id}}</td>
                            <td>{{item.name}}</td>
                            <td>{{item.address}}</td>
                            <td>{{item.entryTime*1000 | formatDate}} {{item.entryTime*1000 | formatDateBehind}}</td>
                            <td>
                                <button type="button" @click="dialogVisible = true;for(var i in addfarmer) addfarmer[i] = item[i];addfarmer.key = key" class="bc4a wh pt5 pr10 pb5 pl10 br5 f16">修改</button>
                                <button type="button" @click="deletefarmer(item.id,key)" class="bcfd wh pt5 pr10 pb5 pl10 br5 f16">删除</button>
                            </td>
                        </tr>
                    </tbody>
                </table>

            </div>

            <!-- 弹窗用于修改和添加农户使用 -->
            <el-dialog :title="addfarmer !== '' ? '修改农户信息' : '新增农户信息'" width="30%" :visible.sync="dialogVisible" top="10%" :center="true">
                
                <el-form label-width="75px" :model="addfarmer" ref="addfarmer" :rules="rules">
                    <el-form-item label="农户名称" prop="name">
                        <el-input placeholder="" v-model="addfarmer.name" clearable></el-input>
                    </el-form-item>

                    <el-form-item label="农户地址" prop="address">
                        <el-input placeholder="" v-model="addfarmer.address" clearable></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button v-if="addfarmer.id === ''" type="primary" @click="farmeradd('addfarmer')">确定</el-button>
                        <el-button v-else type="primary" @click="farmerupdata('addfarmer')">修改</el-button>
                    </el-form-item>
                </el-form>

            </el-dialog>

            <div class="dh_c-c-block mt20" v-if="activecoupon == 1">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-size="pagesize"
                    layout="total, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>

        </div>
    </div>
</template>

<script>
const axios = require('axios')
import {formatDate } from '../js/time.js'
import {timetamp} from '../js/time.js'
export default {
    components: {},
    data() {
        return {
            token: '',
            activecoupon: '1',        //优惠券的导航栏
            radio: '1',              //单选
            farmerdata:[],              //农户数据
            // 查询搜索
            formfarmer:{
                region: '1',
                id: '',
                name: '',
                address: '',
            },
            rules: {
                id: [
                    { required: true, message: '请输入农户ID', trigger: 'blur' },
                ],
                name: [
                    {required: true,message: '请输入农户名称',trigger: 'blur'}
                ],
                address: [
                    { required: true, message: '请输入农户地址', trigger: 'blur' }
                ],
                date1: [
                    { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
                ],
                date2: [
                    { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
                ],
            },
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
            dialogVisible: false,
            addfarmer: {
                id:'',
                key: '',
                name: '',                    //农户名称
                address: '',                 //农户地址
            },
        };
    },
    computed: {},
    watch: {},
    filters: {
        filterstate(state){
            if(state == 1){
                state = "已被领取"
            }else{
                state = "未被领取"
            }
            return state
        },
		formatDate(time){
			var date = new Date(time);
			return formatDate(date, 'yyyy-MM-dd');
		},
		formatDateBehind(time){
			var date = new Date(time);
			return formatDate(date, 'hh:mm:ss')
		}
    },
    methods: {
        // 验证状态清除，写在选框中的change事件，值改变触发
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },

        // 查询（搜索）
        farmerquery(formquery){
            let that = this;
            let data = {current:that.currentPage, size:that.pagesize};
            this.$refs[formquery].validate((valid) => {
                if (valid) {

                    let puppetarr = Object.keys(JSON.parse(JSON.stringify(that.formfarmer)))
                    for(var i of puppetarr)
                    that.formfarmer[i] !== '' && i !== "region" ? data[i] = that.formfarmer[i] : '';
                    let updata= JSON.stringify(data)
                    axios({
                        method: 'post',
                        url: '/api/farmer/list',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> {
                        console.log(resp)
                        that.farmerdata = resp.data.data;
                        that.total = resp.data.code;
                    }).catch( err=> {console.log(err)})

                } else {return false;}
            });
        },

         // 单页条数
        handleSizeChange(val) {
            // console.log(`每页: ${val}条数据`);
            this.pagesize = val;
            this.goodslist()
            // if(that.paging === 1){
            //     that.classifylatt()
            // }else if(that.paging === 2){
            //     that.lookson()
            // }else if(that.paging === 3){
            //     that.inquire()
            // }else{
            //     that.updataclassify()
            // }
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            const that = this;
            that.currentPage = val;
            that.goodslist()
            // if(that.paging === 1){
            //     that.classifylatt()
            // }else if(that.paging === 2){
            //     that.lookson()
            // }else if(that.paging === 3){
            //     that.inquire()
            // }else{
            //     that.updataclassify()
            // }
        },

        // 请求农户数据
        requestfarmer(){
            let that = this;
            let data = {current:that.currentPage, size:that.pagesize};
            let updata = JSON.stringify(data);
            console.log(updata)
            axios({
                method: 'post',
                url: '/api/farmer/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            })
            .then( resp=> {
                // console.log(resp)
                that.farmerdata = resp.data.data;
                that.total = resp.data.code;
                if(that.farmerdata === undefined){
                    sessionStorage.removeItem("token")
                    location.reload()
                }else{return}
            })
            .catch( err=> {console.log(err)})
        },

        // 增加农户
        farmeradd(formadd){
            let that = this;
            let date = new Date()
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            month<10 ? month = '0'+month : month;
            day<10 ? day = '0'+day : day;
            let daytime = year + '-' + month + '-' + day
            this.$refs[formadd].validate((valid) => {
                if(valid){
                    console.log(timetamp(daytime))
                    let data = {name:that.addfarmer.name,address:that.addfarmer.address,entryTime:timetamp(daytime)};
                    let updata = JSON.stringify(data)
                    axios({
                        method: 'post',
                        url: '/api/farmer/add',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> {
                        console.log(resp)
                        if(resp.data.message === "请求成功" && resp.data.data !== ''){
                            that.dialogVisible = false;
                            data.id = resp.data.data
                            that.farmerdata.length < that.pagesize ? that.farmerdata.push(data) : '';
                            that.$message({
                                message: '农户新增成功！',
                                type: 'success'
                            })
                        }else{return}
                        
                    }).catch( err=> {console.log(err)})
                }else{return false}
            })
        },

        // 删除农户
        deletefarmer(id,key){
            let that = this;
            let data = {id: id};
            let updata = JSON.stringify(data)
            axios({
                method: 'post',
                url: '/api/farmer/delete',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            })
            .then( resp=>{
                console.log(resp)
                that.farmerdata.splice(key,1)
            })
            .catch( err=> {console.log(err)})
        },
        
        // 修改农户信息
        farmerupdata(formup){
            let that = this;
            this.$refs[formup].validate((valid) => {
                if(valid){
                    let data = {};
                    for(var o in that.addfarmer) o !== '' ? data[o] = that.addfarmer[o] : '';
                    // console.log(data)
                    let updata = JSON.stringify(data);
                    axios({
                        method: 'post',
                        url: '/api/farmer/update',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> {
                        console.log(resp)
                        if(resp.data.data === "更新成功！"){
                            for(var t in data) that.farmerdata[that.addfarmer.key][t] = data[t]
                        }else{return}
                        that.dialogVisible = false;
                        that.$message({
                            message: '修改成功！',
                            type: 'success'
                        })
                    }).catch( err=> {console.log(err)})
                }else{return false}
            })
        },

        //拿token
        newtoken(){
            let that = this;
            let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
			console.log(updata)
			axios({
				method: 'post',
				url: '/api/getAuthority/manager',
				headers: { 'Content-Type': 'application/json' },
				data: updata
			})
			.then( resp=> {
                that.token = resp.data.data;
				sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                that.requestfarmer();
			}).catch( err=> {})
        }
    },
    created() {},
    mounted() {
        let that = this;
        that.newtoken()
    },
    beforeCreate() {},
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
    /* 默认样式修改 */
    /* button{
        ou
    } */
    .dhzn_farmer{
        height: calc(100% - 56px);
        box-sizing: border-box;
    }
    .dh_c-content{
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: calc(100% - 61px);
        box-sizing: border-box;
    }
    /* 查询优惠券  */
    .dh_c-c-details{
        padding: 10px;
        background-color: #ffffff;
    }
    .dh_ccd-title{
        margin: 0 -10px 10px;
        padding: 0 10px 10px;
        border-bottom: 1px solid #e0e0e0;
    }
    
    /* 数据列表 */
    .dh_ccd-table{
        width: 100%;
        color: #666666;
        border-bottom: 1px solid #e0e0e0;
        border-left: 1px solid  #e0e0e0;
        border-collapse: collapse;
    }
    .dh_ccd-table thead tr{
        background-color: #F2F2F2;
    }
    .dh_ccd-table tbody tr:hover{
        background-color: #F2F2F2;
    }
    .dh_ccd-table th, .dh_ccd-table td{
        min-height: 50px;
        padding: 10px;
        border-top: 1px solid #e0e0e0;
        border-right: 1px solid #e0e0e0;
    }

    /* .dh_ccd-radio{
        height: 50px;
        line-height: 50px;
        padding: 0 30px;
        border-bottom: 1px solid #c7c7c7;
    }
    .dh_ccd-table{
        text-align: center;
        width: 100%;
        border-collapse: collapse;
    }
    .dh_ccd-table>tr:nth-child(even){
        color: white;
        background-color: #b4b4b4;
    }
    .dh_ccd-table>tr>th,.dh_ccd-table>tr>td{
        height: 50px;
    }

    .el-date-editor.el-input{
        width: 100%;
    } */

    /* 分页 */
    .dh_c-c-block{
        text-align: center;
        margin-top: 20px;
    }
</style>